<?php

namespace App\Http\Controllers\Api;

use App\Models\Shop\Product;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Shop\Category;
use DB;

class ProductController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function category()
    {
        $categories = Category::get_categories();
        return compact('categories');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
//        $id = $request->id;
        $product = Product::with('product_galleries')->find($id);
        $recommends = Product::with('product_galleries')->where('id', '<>', $id)->where('is_recommend', 1)->orderBy('sort_order', 'desc')
            ->get();
        return compact('product','recommends');

    }





    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }

    /***
     * 商品列表
     */
    public function product_list(Request $request )
    {
        $where = function ($query) use ($request) {
            $category_id = $request->category_id;
            if ($request->has('category_id') and $request->category_id != '') {
                $product_ids = DB::table('category_product')->where('category_id', $category_id)
                    ->pluck('product_id');
                $query->whereIn('id', $product_ids);
            }
            if ($request->has('searchword') and $request->searchword != '') {
                $search = "%" . $request->searchword . "%";
                $query->where('name', 'like', $search);
            }

        };

        $products = Product::where($where)
            ->orderBy('is_top', "desc")->orderBy('created_at')
            ->get();

        return  compact('products');
    }
    /***
     * 搜索
     */
    public function search()
    {

        $recommends = Product::where('is_recommend', 1)->where('is_onsale', 1)->
        orderBy('created_at')->get();
        $hots = Product::where('is_hot', 1)->where('is_onsale', 1)->
        orderBy('created_at')->get();
        return  compact('recommends','hots');
    }
}
